package com.demo.auth.controller;

import com.demo.auth.common.constants.ImageConstants;
import com.demo.auth.entity.ImageCode;
import com.demo.auth.entity.SmsCode;
import com.demo.auth.service.SmsCodeSender;
import com.demo.auth.until.ImageCodeGenerator;
import com.demo.auth.until.SmsCodeGenerator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于获取验证码 controller
 *
 * @author YT
 * @date 2019-06-04
 */
@RestController
@Slf4j
public class ValidateCodeController {

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    private SmsCodeSender smsCodeSender;

    /**
     * 获取图形验证码
     * 1.首先调用 ImageCodeGenerator 工具类的 createImageCode 生成验证码对象
     * 2.调用 SessionStrategy 把当前的 ImageCode 对象存储在 Session
     * 3.调用 ImageI0.write 将 BufferedImage 对象转换为一个图片格式的文件并写入到response响应流中
     *
     * @param request
     * @param response
     */
    @GetMapping("/code/image")
    @SneakyThrows
    public void getCode(HttpServletRequest request, HttpServletResponse response) {
        ImageCode imageCode = ImageCodeGenerator.createImageCode();
        sessionStrategy.setAttribute(new ServletWebRequest(request), ImageConstants.SESSION_KEY_CODE, imageCode);
        ImageIO.write(imageCode.getImage(), ImageConstants.CODE_TYPE, response.getOutputStream());
    }

    /**
     * 获取短信验证码
     *
     * @param request
     */
    @GetMapping("/sms/code")
    @SneakyThrows
    public void getSms(HttpServletRequest request, HttpServletResponse response) {
        String mobile = ServletRequestUtils.getRequiredStringParameter(request,"mobile");
        SmsCode smsCode = SmsCodeGenerator.createSmsCode();

        Map<String, Object> map = new HashMap<>(16);
        map.put("mobile", mobile);
        map.put("code", smsCode);

        sessionStrategy.setAttribute(new ServletWebRequest(request), "smsCode", map);

        smsCodeSender.sendSmsCode(mobile, smsCode.getCode());
    }
}
